package com.cn.ryc.controller;

import com.cn.ryc.service.DetectionService;
import com.cn.ryc.util.ApiResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;
import java.time.LocalDate;
import java.time.LocalTime;
import java.time.format.DateTimeFormatter;
import java.time.format.DateTimeParseException;
import java.util.List;
import java.util.Map;

@CrossOrigin
@RestController
@RequestMapping("/api/detection")
public class DetectionController {

    @Autowired
    private DetectionService detectionService;

    @PostMapping("/insert")
    public ResponseEntity<ApiResponse<String>> insertDetectionRecords(@RequestBody Map<String, Object> request) {
        String videoUrl = (String) request.get("videoUrl");
        String currentTimeStr = (String) request.get("current_time");
        LocalDateTime detectionTime = null;

        try {
            LocalTime timePart = LocalTime.parse(currentTimeStr, DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
            detectionTime = LocalDateTime.of(LocalDate.now(), timePart);
        } catch (DateTimeParseException e) {
            return ResponseEntity.status(400).body(ApiResponse.error(400, "Invalid time format"));
        }

        List<Map<String, Object>> detections = (List<Map<String, Object>>) request.get("detections");
        return detectionService.insertDetectionRecords(videoUrl, detectionTime, detections);
    }
} 